package org.jeecg.modules.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserDepart;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.mapper.SysDepartMapper;
import org.jeecg.modules.system.mapper.SysUserDepartMapper;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.mapper.SysUserRoleMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysSyncUserService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.common.util.TokenServess;
import org.jeecg.modules.system.vo.SysUserSynVO;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class SysSyncUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysSyncUserService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserDepartMapper sysUserDepartMapper;

    @Autowired
    private SysDepartMapper sysDepartMapper;

    @Autowired
    private ISysDepartService sysDepartService;

    @Override
    public void syncUserData() throws IOException, NoSuchAlgorithmException, InvalidKeyException {

        TokenServess sztyServes = new TokenServess();
        String tokenServe = sztyServes.getTokenServe();

//        QueryWrapper<SysDepart> deparWraper = new QueryWrapper<>();
//        deparWraper.eq("org_category", "2");
//        deparWraper.eq("org_type", "1");
//        List<SysDepart> departList = sysDepartService.list(deparWraper);
        List<SysUserSynVO> sysUserSynVOList = new ArrayList<>();
//        for (SysDepart depart:departList) {
//            String tId =depart.getTId();

            String jsonString = sztyServes.getListAllEmployee(null, null, null, tokenServe);

            // 创建ObjectMapper对象
            ObjectMapper mapper = new ObjectMapper();

            // 将字符串转换为JsonNode对象
            JsonNode jsonNode = mapper.readTree(jsonString);

            // 获取data属性的值
            JsonNode dataNode = jsonNode.get("data");
            if (dataNode.isArray()) {

                for (JsonNode unitNode : dataNode) {
                    String departmentId = String.valueOf(unitNode.get("departmentId")).replace("\"", "");
                    String positionList = String.valueOf(unitNode.get("positionList")).replace("\"", "");
                    String corpId = String.valueOf(unitNode.get("corpId")).replace("\"", "");
                    String mobile = String.valueOf(unitNode.get("mobile")).replace("\"", "");
                    String number = String.valueOf(unitNode.get("number")).replace("\"", "");
                    String telephone = String.valueOf(unitNode.get("telephone")).replace("\"", "");
                    String name = String.valueOf(unitNode.get("name")).replace("\"", "");
                    String id = String.valueOf(unitNode.get("id")).replace("\"", "");
                    String seq = String.valueOf(unitNode.get("seq")).replace("\"", "");
                    String email = String.valueOf(unitNode.get("email")).replace("\"", "");
                    String status = String.valueOf(unitNode.get("status")).replace("\"", "");


                    SysUserSynVO sysUserSynVO = new SysUserSynVO();
                    sysUserSynVO.setTDepartmentId((departmentId != null && !"null".equals(departmentId)) ? departmentId : "");
                    sysUserSynVO.setTPositionList((positionList != null && !"null".equals(positionList)) ? positionList : "");
                    sysUserSynVO.setTCorpId((corpId != null && !"null".equals(corpId)) ? corpId : "");
                    sysUserSynVO.setTMobile((mobile != null && !"null".equals(mobile)) ? mobile : null);
                    sysUserSynVO.setTTelephone((telephone != null && !"null".equals(telephone)) ? telephone : null);
                    sysUserSynVO.setTNumber((number != null && !"null".equals(number)) ? number : "");
                    sysUserSynVO.setTName((name != null && !"null".equals(name)) ? name : "");
                    sysUserSynVO.setTId(id);
                    sysUserSynVO.setTSeq((seq != null && !"null".equals(seq)) ? seq : "");
                    sysUserSynVO.setTEmail((email != null && !"null".equals(email)) ? email : null);
                    sysUserSynVO.setTStatus(status);
                    sysUserSynVOList.add(sysUserSynVO);

                }
            }
//        }
        syncUpdateOrSaveUser(sysUserSynVOList);
    }

    /**
     * 根据传入数智天研的人员数据，更新人员数据
     *
     * @param synUserVOList
     */
    @Transactional(rollbackFor = Exception.class)
    public void syncUpdateOrSaveUser(List<SysUserSynVO> synUserVOList) throws JsonProcessingException {

//        QueryWrapper<SysUser> userWrapper = new QueryWrapper<>();
//        userWrapper.eq("t_corp_id",depart.getTId());
        //数据库人员数据
        List<SysUser> sysUserList = sysUserService.list();
        //更新的人员数据
        List<SysUser> modUserList = new ArrayList<>();
        //新增的人员数据
        List<SysUser> addUserList = new ArrayList<>();
        //数据库中旧的人员数据
        List<SysUser> oldUserList = new ArrayList<>();

        //第一次同步数据
        if (sysUserList == null || sysUserList.size() <= 0) {
            for (SysUserSynVO synUserVO : synUserVOList) {
                String tId = synUserVO.getTId();
                SysUser sysUser = new SysUser();
                sysUser.setRealname(synUserVO.getTName());
                sysUser.setSex(synUserVO.getGender());

                //设置username
                convertToPinyin(sysUser);
                //设置密码
                initPassword(sysUser);
                //设置岗位
                sysUser.setTPositionList(synUserVO.getTPositionList());
                postStr(sysUser);
                sysUser.setPhone(synUserVO.getTMobile());
                sysUser.setWorkNo(synUserVO.getTNumber());
                sysUser.setTelephone(synUserVO.getTTelephone());
                sysUser.setEmail(synUserVO.getTEmail());
                if ("40".equals(synUserVO.getTStatus())) {
                    sysUser.setStatus(2);
                } else {
                    sysUser.setStatus(1);
                }
                sysUser.setDelFlag(CommonConstant.DEL_FLAG_0);

                sysUser.setTId(tId);
                sysUser.setTSeq(synUserVO.getTSeq());
                sysUser.setTCorpId(synUserVO.getTCorpId());
                sysUser.setTDepartId(synUserVO.getTDepartmentId());

                sysUser.setTStatus(synUserVO.getTStatus());

                addUserList.add(sysUser);
            }
            //第二次同步数据
        } else {
            for (SysUserSynVO synUserVO : synUserVOList) {
                String tId = synUserVO.getTId();//张三
                boolean bool = true;
                for (SysUser userVO : sysUserList) {//李四、王五、张三、。。。。
                    if (tId.equals(userVO.getTId())) {
                        userVO.setRealname(synUserVO.getTName());
                        userVO.setSex(synUserVO.getGender());
                        userVO.setPhone(synUserVO.getTMobile());
                        userVO.setWorkNo(synUserVO.getTNumber());
                        userVO.setTelephone(synUserVO.getTTelephone());
                        userVO.setEmail(synUserVO.getTEmail());
                        userVO.setTPositionList(synUserVO.getTPositionList());
                        postStr(userVO);
                        if ("40".equals(synUserVO.getTStatus())) {
                            userVO.setStatus(2);
                        } else {
                            userVO.setStatus(1);
                        }
                        userVO.setTId(synUserVO.getTId());
                        userVO.setTCorpId(synUserVO.getTCorpId());
                        userVO.setTDepartId(synUserVO.getTDepartmentId());
                        userVO.setTSeq(synUserVO.getTSeq());
                        userVO.setTStatus(synUserVO.getTStatus());
                        modUserList.add(userVO);
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    SysUser sysUser = new SysUser();
                    sysUser.setRealname(synUserVO.getTName());
                    //设置username
                    convertToPinyin(sysUser);
                    //设置密码
                    initPassword(sysUser);
                    //设置岗位
                    sysUser.setTPositionList(synUserVO.getTPositionList());
                    postStr(sysUser);
                    sysUser.setSex(synUserVO.getGender());
                    sysUser.setPhone(synUserVO.getTMobile());
                    sysUser.setWorkNo(synUserVO.getTNumber());
                    sysUser.setTelephone(synUserVO.getTTelephone());
                    sysUser.setEmail(synUserVO.getTEmail());
                    if ("40".equals(synUserVO.getTStatus())) {
                        sysUser.setStatus(2);
                    } else {
                        sysUser.setStatus(1);
                    }
                    sysUser.setDelFlag(CommonConstant.DEL_FLAG_0);
                    sysUser.setTId(tId);
                    sysUser.setTSeq(synUserVO.getTSeq());
                    sysUser.setTCorpId(synUserVO.getTCorpId());
                    sysUser.setTDepartId(synUserVO.getTDepartmentId());
                    sysUser.setTStatus(synUserVO.getTStatus());
                    addUserList.add(sysUser);
                }
            }

            //用当前数据库中的单位数据和同步的单位数据对比
            for (SysUser sysUser : sysUserList) {
                String voId = sysUser.getTId();
                boolean bool = true;
                for (SysUserSynVO synUserVO : synUserVOList) {
                    String tId = synUserVO.getTId();
                    if (tId.equals(voId)) {
                        bool = false;
                        break;
                    }
                }
                if (bool) {
                    if (!sysUser.getUsername().equals("admin") && !sysUser.getUsername().equals("admin01")) {
                        sysUser.setStatus(2);
                        oldUserList.add(sysUser);
                    }
                }
            }
        }


        //更新人员数据
        for (SysUser user : modUserList) {
            //1、修改数据
            sysUserService.updateById(user);
            //2 先删后加部门
            sysUserDepartMapper.delete(new QueryWrapper<SysUserDepart>().lambda().eq(SysUserDepart::getUserId, user.getId()));
            //2.1部门
            String departId = user.getTDepartId();
            if (oConvertUtils.isNotEmpty(departId)) {
                QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("t_id",departId);
                queryWrapper.eq("t_org_type","dep");
                SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
                if (sysDepart != null) {
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), sysDepart.getId());
                    sysUserDepartMapper.insert(userDepart);
                }
            }
            //2.2单位
            String corpId = user.getTCorpId();
            if (oConvertUtils.isNotEmpty(corpId)) {
                QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("t_id",corpId);
                queryWrapper.eq("t_org_type","cor");
                SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
                if (sysDepart != null) {
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), sysDepart.getId());
                    sysUserDepartMapper.insert(userDepart);
                }
            }

        }

        //新增人员数据
        for (SysUser user : addUserList) {
            //1.保存数据
            try {
                sysUserService.save(user);
            } catch (Exception e) {
                System.out.println(user.getRealname());
            }

            //2.1部门
            String departId = user.getTDepartId();
            if (oConvertUtils.isNotEmpty(departId)) {
                QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("t_id",departId);
                queryWrapper.eq("t_org_type","dep");
                SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
                if (sysDepart != null) {
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), sysDepart.getId());
                    sysUserDepartMapper.insert(userDepart);
                }
            }
            //2.2单位
            String corpId = user.getTCorpId();
            if (oConvertUtils.isNotEmpty(corpId)) {
                QueryWrapper<SysDepart> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("t_id",corpId);
                queryWrapper.eq("t_org_type","cor");
                SysDepart sysDepart = sysDepartService.getOne(queryWrapper);
                if (sysDepart != null) {
                    SysUserDepart userDepart = new SysUserDepart(user.getId(), sysDepart.getId());
                    sysUserDepartMapper.insert(userDepart);
                }
            }
            //3.设置角色
            String roleId = "1720662357543133185";
            SysUserRole userRole = new SysUserRole(user.getId(), roleId);
            sysUserRoleMapper.insert(userRole);
        }
        ;

//        逻辑删除人员数据-冻结用户
        for (SysUser user : oldUserList) {
            // 处理 user 对象...
            sysUserMapper.updateById(user);
        }
    }


    public void convertToPinyin(@NotNull SysUser sysUser) {

        String realname = sysUser.getRealname();
        // 创建汉语拼音输出格式对象
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 不带声调

        // 将中文名称转换为拼音
        String pinyin = "";
        try {
            for (char c : realname.toCharArray()) {
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { // 判断是否为中文字符
                    String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (pinyinArray != null && pinyinArray.length > 0) {
                        pinyin += pinyinArray[0];
                    }
                } else {
                    pinyin += c;
                }
            }
            sysUser.setUsername(pinyin);
            QueryWrapper<SysUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",pinyin);
            List<SysUser> users = sysUserService.list(queryWrapper);
            if (users.size() > 0) {
                String num = Integer.toString(users.size() + 1);
                pinyin += "0" + num;
                sysUser.setUsername(pinyin);
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
        }

    }


    public void initPassword(@NotNull SysUser sysUser) {
        String salt = oConvertUtils.randomGen(8);
        sysUser.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), "Tyy20230728sysxt@", salt);
        sysUser.setPassword(passwordEncode);

    }

    public void postStr(@NotNull SysUser sysUser) throws JsonProcessingException {
        String posts = "";
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonPost = sysUser.getTPositionList();
        if (oConvertUtils.isNotEmpty(jsonPost)) {
            try {
                Pattern pattern = Pattern.compile("name:(.*?),");
                Matcher matcher = pattern.matcher(jsonPost);
                while (matcher.find()) {
                    String name = matcher.group(1);
                    if ("".equals(posts)) {
                        posts += name;
                    } else {
                        posts += "," + name;
                    }
                }
                sysUser.setPost(posts);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


    }
}
